package com.tavio.tbs.world;

import org.andengine.extension.tmx.TMXLayer;
import org.andengine.extension.tmx.TMXLoader;
import org.andengine.extension.tmx.TMXTileProperty;
import org.andengine.extension.tmx.TMXTiledMap;
import org.andengine.extension.tmx.util.exception.TMXLoadException;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import android.content.res.AssetManager;

import com.tavio.tbs.structure.Position;
import com.tavio.tbs.terrain.TerrainType;

public class WorldMap {

	private TMXTiledMap tmxTiledMap;
	private TMXLoader tmxLoader;
	
	private int numRows;
	private int numColumns;
	private int tileWidth;
	private int tileHeight;
	
	private WorldTile[][] worldMap;
	
	private static WorldMap instance = null;
		
	private WorldMap(){}
	
	public static WorldMap getInstance() {
		if(instance == null)
			instance = new WorldMap();
		return instance;
	}
	
	public void init(String mapFilePath, final AssetManager pAssetManager, final TextureManager pTextureManager, final TextureOptions pTextureOptions, final VertexBufferObjectManager pVertexBufferObjectManager) throws TMXLoadException {
		this.tmxLoader = new TMXLoader(pAssetManager, pTextureManager, TextureOptions.BILINEAR_PREMULTIPLYALPHA, pVertexBufferObjectManager);
		this.tmxTiledMap = tmxLoader.loadFromAsset(mapFilePath);
		
		this.numRows = tmxTiledMap.getTileRows();
		this.numColumns = tmxTiledMap.getTileColumns();
		this.tileWidth = tmxTiledMap.getTileWidth();
		this.tileHeight = tmxTiledMap.getTileHeight();
		
		worldMap = new WorldTile[numColumns][numRows];
		
		for(int i = 0; i < numColumns; i++) {
			for(int j = 0; j < numRows; j++) {
				worldMap[i][j] = new WorldTile(new Position(i,j), null);
				for(TMXTileProperty prop : tmxTiledMap.getTMXTileProperties(tmxTiledMap.getTMXLayers().get(0).getTMXTile(i, j).getGlobalTileID())) {
					if("terrain".equals(prop.getName())) {
						if("woods".equals(prop.getValue()))
							worldMap[i][j].setTerrainType(TerrainType.WOODS);
						else
							worldMap[i][j].setTerrainType(TerrainType.PLAINS);
					}
				}
			}
		}
	}
	
	public TMXTiledMap getTmxTiledMap() {
		return tmxTiledMap;
	}
	
	public TMXLayer getTmxLayer(int layerNum) {
		return tmxTiledMap.getTMXLayers().get(layerNum);
	}
	
	public TerrainType getTerrainTypeAtPosition(Position position) {
		return worldMap[position.getX()][position.getY()].getTerrainType();
	}
	
	public int getNumColumns() {
		return numColumns;
	}
	
	public int getNumRows() {
		return numRows;
	}
	
	public int getTileWidth() {
		return tileWidth;
	}
	
	public int getTileHeight() {
		return tileHeight;
	}
}
